var myApp = angular.module('myApp', [ 'ngGrid', 'ui.select2' ]);
myApp.controller('legsCtrl', function($scope, $http) {
	
	$scope.selectedRows = [];
	
	$scope.selectedRowct=[];
	
	$scope.init = function() {
		$('input[ name= "time"]').datetimepicker({
			minView : "month",
			format : "yyyy-mm-dd hh:ii",
		    todayBtn : "linked",
		    language : "zh-CN",
		    forceParse : false,
		    autoclose : true,
		    todayHighlight : true
		});
		$('input[name = "planaDt1"], input[name = "planaDt2"]').datetimepicker({
			minView : "month",
			format : "yyyy-mm-dd",
			todayBtn : "linked",
			language : "zh-CN",
			forceParse : false,
			autoclose : true,
			todayHighlight : true
		});
		httpPost($http, {"url":ctx + "/client/findListByFirst", "ifBlock" : true}, function(data){
			$scope.clientList = data.dt;
		}, function(){
			toastError("初始化客户列表失败。");
		});
		
		httpPost($http, {"url" : ctx+"/dict/getDictByCd", "params" : {"cd" : "vocation"}, "ifBlock" : true}, function(data){
			$scope.cdList = data.dt;	
		}, function(){
			toastError("初始化业务类型列表失败。");
		});	
	}; 
	
	$scope.init();
	
	$scope.pagingOptions = {
		pageSizes : [ 20, 50, 100 ],
		pageSize : 20,
		currentPage : 1,
		onQueryFlag : false
	};
	
	$scope.$watch('pagingOptions', function(newVal, oldVal) {
		if (newVal !== oldVal/* && newVal.currentPage !== oldVal.currentPage*/) {
			$scope.query();
		}
	}, true);
	
	$scope.gridOptions = {
		data : 'dt',
		totalServerItems : 'tt',
		columnDefs : [
		{
			field : "id",
			displayName : "ID", visible : false
		},
		{
			field : "orderId",
			displayName : "orderId", visible : false
		},
		{
			field : "clientName",
			displayName : "客户",
			width : 180
		},
		{
			field : "orderCd",
			displayName : "订单编号",
			width : 160
		},
		{
			field : "legs_no",
			displayName : "分段订单号",
			width : 160
		},
		{
			field : "ttranslocationName",
			displayName : "目的地",
			width : 160
		},
		{
			field : "toAddr",
			displayName : "收货方地址",
			width : 300
		},
		{
			field : "quantity",
			displayName : "件数",
			width : 160
		},
		{
			field : "weight",
			displayName : "重量",
			width : 160
		},
		{
			field : "volume",
			displayName : "体积",
			width : 160
		},
		{
			field : "palletsum",
			displayName : "托数",
			width : 160
		},
		{
			field : "statusName",
			displayName : "订单状态",
			width : 120
		},
		{
			field : "stName",
			displayName : "状态",
			width : 120
		},
		{
			field : "account",
			displayName : "配送异常情况",
			width : 300
		},
		{
			field : "rtime",
			displayName : "退货时间",
			width : 160,
			cellFilter : "date:'yyyy-MM-dd HH:mm'"
		},
		{
			field : "driverName",
			displayName : "司机",
			width : 120
		},
		{
			field : "vehicleCd",
			displayName : "车牌号",
			width : 120
		},
		{
			field : "vocationName",
			displayName : "业务类型",
			width : 120
		},
		{
			field : "shipment_methodName",
			displayName : "运输方式",
			width : 120
		},
		{
			field : "ftranslocationName",
			displayName : "出发地",
			width : 160
		},
		{
			field : "formName",
			displayName : "发货方名称",
			width : 250
		},
		{
			field : "formlikeName",
			displayName : "发货方联系人",
			width : 120
		},
		{
			field : "formPhone",
			displayName : "发货方电话",
			width : 120
		},
		{
			field : "formAddr",
			displayName : "发货方地址",
			width : 250
		},
		{
			field : "toName",
			displayName : "收货方名称",
			width : 250
		},
		{
			field : "tolikeName",
			displayName : "收货方联系人",
			width : 120
		},
		{
			field : "toPhone",
			displayName : "收货方电话",
			width : 120
		},
		{
			field : "shipmentCd",
			displayName : "调度单号",
			width : 160
		},
		{
			field : "expense",
			displayName : "一口价",
			width : 160
		},
		{
			field : "shipmentExpese",
			displayName : "调度单一口价",
			width : 160
		},
		{
			field : "component",
			displayName : "拆单标识",
			width : 120
		},
		{
			field : "waveName",
			displayName : "波次",
			width : 160
		},
		{
			field : "pcTime",
			displayName : "派车时间",
			width : 160,
			cellFilter: "date:'yyyy-MM-dd HH:mm'"
		},
		{
			field : "rkTime",
			displayName : "车辆入库时间",
			width : 160,
			cellFilter: "date:'yyyy-MM-dd HH:mm'"
		},
		{
			field : "ckTime",
			displayName : "车辆出库时间",
			width : 160,
			cellFilter: "date:'yyyy-MM-dd HH:mm'"
		},
		{
			field : "ordertime",
			displayName : "开单时间",
			width : 160,
			cellFilter: "date:'yyyy-MM-dd HH:mm'"
		},
		{
			field : "billtime",
			displayName : "计费周期",
			width : 160,
			cellFilter: "date:'yyyy-MM-dd HH:mm'"
		},
		{
			field : "planltime",
			displayName : "计划发车时间",
			width : 160,
			cellFilter: "date:'yyyy-MM-dd HH:mm'"
		},
		{
			field : "leavetime",
			displayName : "发车时间",
			width : 160,
			cellFilter: "date:'yyyy-MM-dd HH:mm'"
		},
		{
			field : "planatime",
			displayName : "计划到达时间",
			width : 160,
			cellFilter: "date:'yyyy-MM-dd HH:mm'"
		},
		{
			field : "arrivetime",
			displayName : "到达时间",
			width : 160,
			cellFilter: "date:'yyyy-MM-dd HH:mm'"
		},
		],
		enablePaging : true,
		pagingOptions : $scope.pagingOptions,
		enableCellEdit : true,
		showSelectionCheckbox : true,
		selectedItems : $scope.selectedRows,
		plugins : [ /*new ngGridFlexibleHeightPlugin()*/ ],
		i18n : 'zh-cn', rowHeight : 21, footerRowHeight : 35,
		showFooter : true
	};

	$scope.query = function() {
		closeModal($("#queryFormModal"));
		var requestBody = {
			pageNb : $scope.pagingOptions.currentPage,
			pageSize : $scope.pagingOptions.pageSize,
			ffMap : $scope.queryForm
		};
		setTimeout(function() {
			httpPost($http, {"url":ctx + '/legs/findListBy', "data" : requestBody, "ifBlock" : true}, function(data){
				$scope.tt = data.tt;
				$scope.dt = data.dt;
				$scope.gridOptions.$gridScope.toggleSelectAll(false);
				if(data.dt.length === 0){
					toastWarning("没有找到符合查询条件的记录。");
				};
			}, function(errMsg){
				toastError("查询失败。" + errMsg);
			});
		}, 100);
	};

	$scope.onQuery = function(){
		$scope.pagingOptions.onQueryFlag = !$scope.pagingOptions.onQueryFlag;
		$scope.pagingOptions.currentPage = 1;
	};

	$scope.refresh = function(){
		hideShadow();
		var date= (new Date());
		var now = date.getFullYear() + "-" + (parseInt(date.getMonth()) + 1) + "-" + ((date.getDate() > 9) ? date.getDate() : "0" + date.getDate());
		if($scope.queryForm.planaDt1 == undefined){
			$scope.queryForm.planaDt1 = now;
		};
		if($scope.queryForm.planaDt2 == undefined){
			$scope.queryForm.planaDt2 = now;
		};
		$scope.onQuery();	
	};
		
		//订单明细
		$scope.pagingOption = {
				pageSizes : [ 20, 50, 100 ],
				pageSize : 20,
				currentPage : 1,
				onQueryFlag : false
			};
			
			$scope.$watch('pagingOption', function(newVal, oldVal) {
				if (newVal !== oldVal/* && newVal.currentPage !== oldVal.currentPage*/) {
					$scope.query1();
				}
			}, true);
			
			$scope.gridOption = {
				data : 'd',
				totalServerItems : 't',
				columnDefs : [
				{
					field : "id",
					displayName : "ID", visible : false
				},
				{
					field : "lineno",
					displayName : "行号",
					width : 160
				},
				{
					field : "productName",
					displayName : "货物名称",
					width : 160
				},
				{
					field : "lot",
					displayName : "批号",
					width : 160
				},
				{
					field : "statusName",
					displayName : "审核结果",
					width : 160
				},
				{
					field : "unit",
					displayName : "包装",
					width : 160
				},
				{
					field : "quantity",
					displayName : "数量",
					width : 160
				},
				{
					field : "weight",
					displayName : "重量",
					width : 160
				},
				{
					field : "volume",
					displayName : "体积",
					width : 160
				}
				],
				enablePaging : true,
				pagingOptions : $scope.pagingOption,
				enableCellEdit:true,
				showSelectionCheckbox : true,
				selectedItems : $scope.selectedRow,
				i18n: 'zh-cn', rowHeight : 21, footerRowHeight : 35, //plugins : [/*new ngGridFlexibleHeightPlugin()*/ ],
				showFooter : true
			};
			
			
			$scope.query1 = function() {
				var requestBody = {
					pageNb : $scope.pagingOption.currentPage,
					pageSize : $scope.pagingOption.pageSize,
					ffMap : $scope.queryForm1
				};
				setTimeout(function() {
					httpPost($http, {"url":ctx + '/orderDetail/findListBy', "data" : requestBody, "ifBlock" : false}, function(data){
						$scope.t = data.tt;
						$scope.d = data.dt;
						$scope.gridOption.$gridScope.toggleSelectAll(false);
					}, function(errMsg){
						toastError("查询失败。" + errMsg);
					});
				}, 100);
			};
		
		//删除分段订单
		$scope.del = function(){
			hideShadow();
			var ids = [];
			var object = [];
			var component = [];
			$.each($scope.selectedRows, function(idx, obj){
				console.log(obj);
				if(obj.component == '竖拆'){
					component.push(obj.component);
				}
				ids.push(obj.id);
				object.push(obj);
			});
			if(component.length != object.length){
				alert("删除失败");
			}else{
				dialogConfirm("是否确认删除选择的" + $scope.selectedRows.length + "条分段单？", function(){
					httpPost($http, {"url":ctx + '/legs/del',"data" : object,"params" : {"ids":ids}, "ifBlock" : true}, function(data){
						$scope.onQuery();
					}, function(errMsg){
						toastError("存在下级分段订单还没删除，请先删除下级分段订单。");
					});
				});
			}
		};
		
	//导出
	$scope.onOpenExportFormModal = function(){
		var params = $scope.queryForm;
		var str = jQuery.param(params);
		window.open(ctx  + '/legs/export?' + str);
	};
	
	//导入
	$scope.import = function(){
		$scope.importForm = {};
		$scope.importForm.importUrl = "/legs/import";
		$("input[name = 'file']").css("width","200px").css("height","30px").css("padding-bottom","2px");
		$(".col-sm-3").width(30);
		openModal($("#importFormModal"));
	};
	
	$scope.onImport = function(){
		closeModal($("#importFormModal"));
		$("form[name = 'importFormForm']").submit();
	};
	
	//下载模板
	$scope.onExportTemplate = function(){
		if(isNull($scope.importForm) || isNull($scope.importForm.importUrl)){
			toastWarning("请选择导入项，以下载相应模板。");
			return;
		}
		window.open(ctx + $scope.importForm.importUrl + '/template');
	};
	
	//utils
	$scope.onClearSelectedRows = function() {
		$scope.gridOptions.$gridScope.toggleSelectAll(false);
	};
	
	//crud
	var list = [];
	var list1 = [];
	$scope.onOpenQueryFormModal = function() {
		if(list.length === 0){
			httpPost($http, {"url":ctx + "/dict/getDictByCd", "params" : {"cd" : "shipment"}, "ifBlock" : true}, function(data){
				$.each(data.dt, function(idx, obj){
					list.push(obj);
				});	
				httpPost($http, {"url":ctx + "/dict/getDictByCd", "params" : {"cd" : "receiptStatus"}, "ifBlock" : true}, function(data){
					$.each(data.dt, function(idx, obj){
						list.push(obj);
					});	
				});
			});
			$scope.statusList = list;
		}
		if(list1.length === 0){
			httpPost($http, {"url":ctx+"/dict/getDictByCd", "params":{"cd" : "shipment"}, "ifBlock" : true}, function(data){
				for(var i = 0; i < data.dt.length; i++){
					if(data.dt[i]['descr'] == 'shipment' || data.dt[i]['descr'] == 'shipmentEd' || data.dt[i]['descr'] == 'onway' || data.dt[i]['descr'] == 'arrive'){
						list1.push(data.dt[i]);
					}
				}	
			});
			$scope.stList = list1;
		}
		var date = (new Date());
		var now = date.getFullYear() + "-" + (parseInt(date.getMonth()) + 1) + "-" + ((date.getDate() > 9) ? date.getDate() : "0" + date.getDate());
		if($scope.queryForm.planaDt1 == undefined){
			$scope.queryForm.planaDt1 = now;
		};
		if($scope.queryForm.planaDt2 == undefined){
			$scope.queryForm.planaDt2 = now;
		};
		hideShadow();
		openModal($("#queryFormModal"));
	};
	
	//派车，车辆入库，车辆出库，发车，运抵确认。
	$scope.onOpenConfirmFormModal = function(type) {
		$scope.editForm = {};
		if(type == 'pc'){
			$('h4').text('派车确认');
			$scope.editForm.status = 'sendCar';
		}else if(type == 'rk'){
			$('h4').text('车辆入库确认');
			$scope.editForm.status = 'instorage';
		}else if(type == 'ck'){
			$('h4').text('车辆出库确认');
			$scope.editForm.status = 'outstorage';
		}else if(type == 'fy'){
			$('h4').text('发运确认');
			$scope.editForm.status = 'onway';
		}else if(type == 'yd'){
			$('h4').text('运抵确认');
			$scope.editForm.status = 'arrive';
		}
		var date= (new Date());
		var now = date.getFullYear() + "-" + (parseInt(date.getMonth()) + 1) + "-" + ((date.getDate() > 9) ? date.getDate() : "0" + date.getDate()) + " " + ((date.getHours()> 9) ? date.getHours() : "0" + date.getHours()) + ":" + ((date.getMinutes() > 9) ? date.getMinutes() : "0" + date.getMinutes());
		$scope.editForm.time = now;
		hideShadow();
		openModal($("#confirmFormModal"));
	};
	$scope.Confirm = function(){
		closeModal($("#confirmFormModal"));
		var selectedRowIds = [];
		var selectedShipmentIds = [];
		var orderIds = [];
		var object = [];
		$.each($scope.selectedRows, function(idx, obj){
			if($scope.editForm.status == 'arrive'){
				object.push(obj);
			}
			selectedRowIds.push(obj.id);
			var orderId = $scope.selectedRows[idx]['orderId'];
			if(jQuery.inArray( orderId, orderIds ) < 0){
				orderIds.push(orderId);
			}
			var shipmentId=$scope.selectedRows[idx]['shipmentId'];
			if(jQuery.inArray( shipmentId, selectedShipmentIds ) < 0){
				selectedShipmentIds.push(shipmentId);
			}
		});
		if($scope.editForm.status == 'onway' || $scope.editForm.status == 'arrive'){
			httpPost($http, {"url":ctx + '/legs/updStByIds', "data" : object, "params": {"ids" : selectedRowIds, "st" : $scope.editForm.status}, "ifBlock" : true}, function(data){

			});
		}
		httpPost($http, {"url":ctx + '/legs/updTime', "params": {"ids" : selectedRowIds, "time" : $scope.editForm.time, "status" : $scope.editForm.status, "shipmentIds" : selectedShipmentIds,"orderIds" : orderIds}, "ifBlock" : true}, function(data){
			$scope.query();
		});
	};
	
	//配送异常情况登记
	$scope.onOpenEditFormModalPs = function(){
		hideShadow();
		var id = $scope.selectedRows[0]['orderId']; 
		httpGet($http, {"url":ctx + '/orderHead/id/' + id, "ifBlock":true}, function(data){
			$scope.editFormPs = data.dt;
		}, function(errMsg){
			toastWarning("查询此笔记录失败。");
		});
		openModal($("#editFormModalPs"));
	};
	$scope.ps = function(){
		closeModal($("#editFormModalPs"));
		httpPost($http, {"url":ctx + '/orderHead/ps',"params": {"id":$scope.editFormPs.id, "account" : $scope.editFormPs.account}, "ifBlock" : true}, function(data){
			$scope.onQuery();
		});
	};
	
	//退货确认
	$scope.onOpenEditFormModalRe = function(){
		$scope.editFormR = {};
		var date= (new Date());
		var now = date.getFullYear() + "-" + (parseInt(date.getMonth()) + 1) + "-" + ((date.getDate() > 9) ? date.getDate() : "0" + date.getDate()) + " " + ((date.getHours() > 9) ? date.getHours() : "0" + date.getHours()) + ":" + ((date.getMinutes() > 9) ? date.getMinutes() : "0" + date.getMinutes());
		$scope.editFormR.rtime = now;
		hideShadow();
		openModal($("#editFormModalRe"));
	};
 	
	$scope.rConfirm = function(){
		closeModal($("#editFormModalRe"));
		var orderIds = [];
		$.each($scope.selectedRows, function(idx, obj){
			var orderId = $scope.selectedRows[idx]['orderId'];
			if(jQuery.inArray( orderId, orderIds ) < 0){
				orderIds.push(orderId);
			}
		});
		httpPost($http, {"url":ctx + '/orderHead/return', "params":{"ids" : orderIds, "rtime" : $scope.editFormR.rtime}, "ifBlock" : true}, function(data){
			$scope.query();
		});
	};
	
	//拆单
	$scope.onOpenEditFormModalCd = function() {
		$scope.orderCd = true;
		$scope.clientCd = true;
		var selectedRowsLength = $scope.selectedRows.length;
		if(selectedRowsLength > 1) { toastWarning("请选择一笔记录进行拆单。"); return; }
		httpGet($http, {"url":ctx + '/legs/id/' + $scope.selectedRows[0]['id'], "ifBlock" : true}, function(data){
			$scope.editFormCd = data.dt;
		}, function(errMsg){
			toastWarning("查询此笔记录失败。");
		});
		hideShadow();
		openModal($("#editFormModalCd"));
	};
	$scope.takePart = function(){
		closeModal($("#editFormModalCd"));
		dialogConfirm("是否确认进行此拆单操作。", function(){
			httpPost($http, {"url":ctx + '/legs/save', "data" : $scope.editFormCd, "ifBlock" : true}, function(data){
				toastSuccess("保存成功");
				$scope.onQuery();
			}, function(errMsg){
				toastError("这个单已经拆过或者数据有误！");
			});
		});
	};
	
	//指定波次
	$scope.zdbc = function(){
		$scope.editFormBc = {};
		hideShadow();
		openModal($("#editFormModalBc"));
	};
	
	$scope.zdbcpz = function(){
		closeModal($("#editFormModalBc"));
		var waveIds = [];
		$.each($scope.selectedRows, function(idx, obj){
			waveIds.push(obj.id);
		});
		httpPost($http, {"url":ctx + '/legs/updStByWaveIds',"params": {"ids" : waveIds, "waveId" : $scope.editFormBc.waveId}, "ifBlock" : true}, function(data){
			$scope.onQuery();
		});
	};
	
	$scope.onOpenEditFormModal = function(type, id) {
		var orderId = 0;
		if(type == "add"){
			$scope.editForm = {};
		}else if(type == "upd"){
			if($scope.selectedRows.length != 1) { toastWarning("请选择一笔记录进行编辑。"); return; }
			orderId = $scope.selectedRows[0]['orderId'];
			$scope.editForm = $scope.selectedRows[0];	
		}
		ids = {"orderId":orderId};
		$scope.onQuery1 = function(){
			$scope.pagingOption.onQueryFlag = !$scope.pagingOption.onQueryFlag;
			$scope.pagingOption.currentPage = 1;
			$scope.queryForm1 = ids;
		};	
		$scope.onQuery1();
		hideShadow();
		openModal($("#editFormModal"));
		$("#editFormModal .modal-body").css("padding","3px");
		$(".modal-body").css("overflow","hidden");
	};
	$scope.onSaveEditForm = function(){
		closeModal($("#editFormModal"));
		httpPost($http, {"url":ctx + '/legs/save', "data" : $scope.editForm, "ifBlock" : true}, function(data){
			toastSuccess("保存成功");
			$scope.query();
		}, function(errMsg){
			toastError("保存失败,您输入的信息有误，请检查正确之后再保存。" + errMsg);
		});
	};
	
	//右键菜单功能
	$('#mainDataBlock').contextMenu('menu', {
	      //菜单项样式
	      itemStyle: {
	        fontFamily : 'verdana',
	        backgroundColor : '#F0F0F0',
	        border: 'none',
	        padding: '4px'
	      },
	      //菜单项鼠标放在上面样式
	      itemHoverStyle: {
	        border: '1px solid #fff'
	      },
	      onShowMenu: function(e, menu) {
	    	var sts = [];
	  		var statuss = [];
	  		for(var i = 0; i < $scope.selectedRows.length; i++){
	  			var st = $scope.selectedRows[i]['st'];
	  			if(jQuery.inArray( st, sts ) < 0){
	  				sts.push(st);
	  			}
	  			var status = $scope.selectedRows[i]['status'];
	  			if(jQuery.inArray( status, statuss ) < 0){
	  				statuss.push(status);
	  			}
	  		} 
	  		
	  		if($scope.selectedRows.length === 0){
		          $('#del, #upd,#confirm,#in,#out,#send,#arrive,#specify,#refresh1,#excrete,#return,#ps', menu).remove();
	  		}else if($scope.selectedRows.length === 1){
	  			  if(sts[0] == 'shipment'){
			          $('#confirm,#in,#out,#send,#arrive,#specify,#refresh1,#return,#ps', menu).remove();
	  			  }else{
	  				if(statuss.length === 1 && statuss[0] === 'ARRIVED'){
	  					$('#excrete,#return', menu).remove();
	  				}else if(statuss.length === 1 && statuss[0] ==='sendCar'){
		        		$('#excrete,#confirm,#return', menu).remove();
		        	}else if(statuss.length === 1 && statuss[0] ==='instorage'){
		        		$('#excrete,#confirm,#in,#return', menu).remove();
		        	}else if(statuss.length === 1 && statuss[0] ==='outstorage'){
		        		$('#excrete,#confirm,#in,#out,#return', menu).remove();
		        	}else if(statuss.length === 1 && statuss[0] ==='onway'){
		        		$('#excrete,#confirm,#in,#out,#send,#return', menu).remove();
		        	}else if(statuss.length === 1 && statuss[0] ===' arrive'){
		        		$('#excrete,#confirm,#in,#out,#send,#arrive,#ps', menu).remove();
		        	}else{
		  	          $('#del,#confirm,#in,#out,#send,#arrive,#specify,#refresh1,#excrete,#return,#ps', menu).remove();
		        	}
	  			  }
	  		}else{
	  			if(sts[0] == 'shipment' || sts.length > 1){
		  	          $('#confirm,#upd,#in,#out,#send,#arrive,#specify,#refresh1,#excrete,#return,#ps', menu).remove();
	  			}else{
	  				if(statuss.length === 1 && statuss[0] === 'ARRIVED'){
	  					$('#excrete,#upd,#return,#ps', menu).remove();
	  				}else if(statuss.length === 1 && statuss[0] === 'sendCar'){
		        		$('#excrete,#upd,#confirm,#return,#ps', menu).remove();
		        	}else if(statuss.length === 1 && statuss[0] === 'instorage'){
		        		$('#excrete,#upd,#confirm,#in,#return,#ps', menu).remove();
		        	}else if(statuss.length === 1 && statuss[0] === 'outstorage'){
		        		$('#excrete,#upd,#confirm,#in,#out,#return,#ps', menu).remove();
		        	}else if(statuss.length === 1 && statuss[0] === 'onway'){
		        		$('#excrete,#upd,#confirm,#in,#out,#send,#return,#ps', menu).remove();
		        	}else if(statuss.length === 1 && statuss[0] === 'arrive'){
		        		$('#excrete,#upd,#confirm,#in,#out,#send,#arrive,#ps', menu).remove();
		        	}else{
		  	          $('#del,#confirm,#upd,#in,#out,#send,#arrive,#specify,#refresh1,#excrete,#return,#ps', menu).remove();
		        	}
	  			}
	  		}
	        return menu;
	      }
		});
});